package com.magic.himalaya.presenters;

import android.nfc.Tag;

import com.magic.himalaya.R;
import com.magic.himalaya.base.BaseApplication;
import com.magic.himalaya.interfaces.IPlayViewCallBack;
import com.magic.himalaya.interfaces.IPlayerPresenter;
import com.magic.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis;
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException;

import java.util.ArrayList;
import java.util.List;

import okhttp3.internal.Util;

/**
 * @description:
 * @create: Create by Magic on 2022/1/23.
 */
public class PlayerPresenter implements IPlayerPresenter, IXmAdsStatusListener, IXmPlayerStatusListener {
    private static final String TAG = PlayerPresenter.class.getSimpleName();

    private final List<IPlayViewCallBack> mIPlayViewCallBacks = new ArrayList<>();
    private static PlayerPresenter trackPresenter = null;   //此类单例实体
    private final List<Track> mTrackList = new ArrayList<>();//声音列表
    private int mPosition = 0;//当前播放列表位置
    private final XmPlayerManager mXmPlayerManager;//喜马拉雅播放器

    /**
     * 获得喜马拉雅播放器并初始化
     */
    private PlayerPresenter() {
        mXmPlayerManager = XmPlayerManager.getInstance(BaseApplication.getsAppContext());
        mXmPlayerManager.init();//初始化播放器
        //广告事件监听
        mXmPlayerManager.addAdsStatusListener(this);
        //播放监听回调
        mXmPlayerManager.addPlayerStatusListener(this);
    }

    /**
     * 设置播放器中的声音列表和当前播放的位置
     *
     * @param tracks   声音列表
     * @param position 播放位置
     */
    public void setMTracks(List<Track> tracks, int position) {
        this.mTrackList.clear();
        this.mTrackList.addAll(tracks);
        this.mPosition = position;
        addPlayerList();//加入至播放列表
    }

    /**
     * 用于从主页面进入播放器页面的方法
     */
    public void toPlayer(int position){

    }

    /**
     * 获取当前正在播放的声音
     *
     * @return
     */
    public Track getTrack() {
        mPosition = mXmPlayerManager.getCurrentIndex();
        return mTrackList.get(mPosition);
    }

    public Track getTrackNotByPosition(){
        return (Track) mXmPlayerManager.getCurrSound();
    }

    /**
     * 获取实例 单例模式
     *
     * @return
     */
    public static PlayerPresenter getInstance() {
        if (trackPresenter == null) {
            synchronized (PlayerPresenter.class) {
                if (trackPresenter == null)
                    trackPresenter = new PlayerPresenter();
            }
        }
        return trackPresenter;
    }

    /**
     * 加入播放器 播放列表
     */
    public void addPlayerList() {
        mXmPlayerManager.playList(mTrackList, mPosition);
    }

    public boolean hasPlayerList(){
        List<Track> playList = mXmPlayerManager.getPlayList();
        return playList != null && playList.size() != 0;//如果播放器列表里面有声音则返回true否则false
    }

    //====================  以下业务层实现  ============================

    /**
     * 开始播放
     */
    @Override
    public void play() {
        mXmPlayerManager.play();
        LogUtil.d(TAG, "播放器开始播放");
    }

    /**
     * 暂停播放
     */
    @Override
    public void pause() {
        mXmPlayerManager.pause();
        LogUtil.d(TAG, "播放器暂停播放");
    }

    /**
     * 停止播放器
     */
    @Override
    public void stop() {
        mXmPlayerManager.stop();
    }

    /**
     * 上一首
     */
    @Override
    public void playpre() {
        if (mXmPlayerManager != null) {
            if (mXmPlayerManager.hasPreSound()) {
                mXmPlayerManager.playPre();
                for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                    callBack.onPrePlay(getTrack());
                }
            } else {
                for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                    callBack.toast("没有上一首");
                }
            }
        }
    }

    /**
     * 下一首
     */
    @Override
    public void playnext() {
        if (mXmPlayerManager != null) {
            if (mXmPlayerManager.hasNextSound()) {
                mXmPlayerManager.playNext();
                for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                    callBack.onPrePlay(getTrack());
                }
            } else {
                for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                    callBack.toast("没有下一首");
                }
            }
        }
    }

    /**
     * 将播放器播放模式切换后，通知UI切换播放模式
     *
     * @param playMode
     */
    @Override
    public void switchPlayMode(XmPlayListControl.PlayMode playMode) {
        for (int i = 0; i < 5; i++) {
            //判断当前播放模式在播放模式枚举中的坐标
            if (XmPlayListControl.PlayMode.getIndex(i) == playMode) {
                if (i < 4) {
                    //将播放模式改为下一种
                    playMode = XmPlayListControl.PlayMode.getIndex(i + 1);
                    break;
                } else {
                    //如果当前播放模式是最后一种，则设置成第一种
                    playMode = XmPlayListControl.PlayMode.getIndex(0);
                    break;
                }
            }
        }
        if (mXmPlayerManager != null) {
            //设置播放器播放模式
            mXmPlayerManager.setPlayMode(playMode);
            //更换后播放模式后在UI上通知更改成了什么播放模式
            switch (playMode) {
                case PLAY_MODEL_SINGLE://单曲播放
                    for (IPlayViewCallBack callBack : mIPlayViewCallBacks)
                        callBack.toast("单曲播放");
                    break;
                case PLAY_MODEL_SINGLE_LOOP://单曲循环播放
                    for (IPlayViewCallBack callBack : mIPlayViewCallBacks)
                        callBack.toast("单曲循环播放");
                    break;
                case PLAY_MODEL_LIST://列表播放
                    for (IPlayViewCallBack callBack : mIPlayViewCallBacks)
                        callBack.toast("列表播放");
                    break;
                case PLAY_MODEL_LIST_LOOP://列表循环
                    for (IPlayViewCallBack callBack : mIPlayViewCallBacks)
                        callBack.toast("列表循环播放");
                    break;
                case PLAY_MODEL_RANDOM://随机播放
                    for (IPlayViewCallBack callBack : mIPlayViewCallBacks)
                        callBack.toast("随机播放");
                    break;
            }
            //通知UI进行播放模式图标更换
            for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                callBack.onPlayModeChange(playMode);
            }
        }
    }

    /**
     * 获得当前的播放模式
     *
     * @return
     */
    public XmPlayListControl.PlayMode getPlayMode() {
        return mXmPlayerManager.getPlayMode();
    }

    /**
     * 设置成当前的播放器播放模式的图标
     */
    public void initPlayMode() {
        XmPlayListControl.PlayMode playMode = getPlayMode();
        for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
            callBack.onPlayModeChange(playMode);
        }
    }

    /**
     * 让UI回调渲染播放列表，和当前正在播放的位置
     */
    @Override
    public void playList() {
        if (mXmPlayerManager != null) {
            for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                callBack.onPlayList(mXmPlayerManager.getPlayList());
            }
        }
    }

    /**
     * 滑动图片集数据获取，播放默认
     *
     * @param index
     */
    @Override
    public void playByIndex(int index) {
        if (mXmPlayerManager != null) {
            mPosition = index;
            mXmPlayerManager.play(index);
            for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                callBack.onListLoaded(mTrackList, index);
            }
        }
    }

    /**
     * 用于渲染播放器图片集，获取当前播放的位置
     * @return
     */
    @Override
    public int getCurrentIndex() {
        if (mXmPlayerManager != null) {
            return mXmPlayerManager.getCurrentIndex();
        }
        return mPosition;
    }

    /**
     * 拖动进度条
     *
     * @param progress
     */
    @Override
    public void seekTo(int progress) {
        mXmPlayerManager.seekTo(progress);
    }

    /**
     * 是否正在播放
     *
     * @return
     */
    @Override
    public boolean isPlaying() {
        if (mXmPlayerManager.isPlaying()) {
            for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                callBack.onPlayStart();
            }
        }else{
            for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
                callBack.onPlayStop();
            }
        }
        return mXmPlayerManager.isPlaying();
    }

    /**
     * 播放推荐的第一个专辑
     */
    @Override
    public void playingFirst() {

    }

    @Override
    public void registerViewCallBack(IPlayViewCallBack iPlayViewCallBack) {
        if (!mIPlayViewCallBacks.contains(iPlayViewCallBack)) {
            mIPlayViewCallBacks.add(iPlayViewCallBack);
        }
    }

    @Override
    public void unRegisterViewCallBack(IPlayViewCallBack iPlayViewCallBack) {
        mIPlayViewCallBacks.remove(iPlayViewCallBack);
    }
    //====================  业务层实现 end ============================


    //=========================  广告监听事件 start =============================
    @Override
    public void onStartGetAdsInfo() {
        LogUtil.d(TAG, "开始获取广告物料...");
    }

    @Override
    public void onGetAdsInfo(AdvertisList advertisList) {
        LogUtil.d(TAG, "获取广告物料成功...");

    }

    @Override
    public void onAdsStartBuffering() {
        LogUtil.d(TAG, "广告开始缓冲...");

    }

    @Override
    public void onAdsStopBuffering() {
        LogUtil.d(TAG, "广告结束缓冲...");

    }

    @Override
    public void onStartPlayAds(Advertis advertis, int i) {
        LogUtil.d(TAG, "开始播放广告...");

    }

    @Override
    public void onCompletePlayAds() {
        LogUtil.d(TAG, "广告播放完毕...");

    }

    @Override
    public void onError(int what/**错误类型*/, int extra /**错误的额外信息*/) {
        LogUtil.d(TAG, "播放广告错误...");

    }
    //==========================  广告监听事件 end =============================


    //==========================  播放器监听事件  ==============================
    @Override
    public void onPlayStart() {
        LogUtil.d(TAG, "Listener开始播放");
        for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
            callBack.onPlayStart();
        }
    }

    @Override
    public void onPlayPause() {
        for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
            callBack.onPlayPause();
        }
        LogUtil.d(TAG, "Listener暂停播放");

    }

    @Override
    public void onPlayStop() {
        for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
            callBack.onPlayPause();
        }
        LogUtil.d(TAG, "Listener停止播放");

    }

    @Override
    public void onSoundPlayComplete() {
        for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
            callBack.onPlayPause();
        }
        LogUtil.d(TAG, "Listener播放完成");

    }

    @Override
    public void onSoundPrepared() {
        LogUtil.d(TAG, "Listener播放器准备完毕");

    }

    @Override
    public void onSoundSwitch(PlayableModel playableModel, PlayableModel playableModel1) {
        for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
            callBack.setViewData(getTrack());
        }
        LogUtil.d(TAG, "Listener切歌");

    }

    @Override
    public void onBufferingStart() {
        LogUtil.d(TAG, "Listener开始缓冲");

    }

    @Override
    public void onBufferingStop() {
        LogUtil.d(TAG, "Listener结束缓冲");

    }

    @Override
    public void onBufferProgress(int i) {
        LogUtil.d(TAG, "Listener缓冲进度回调");

    }

    @Override
    public void onPlayProgress(int intcurrPos, int duration) {
        for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
            callBack.onNowPlayTime(intcurrPos, duration);
        }
        LogUtil.d(TAG, "Listener播放进度回调intcurrPos:" + intcurrPos + ",duration:" + duration);

    }

    @Override
    public boolean onError(XmPlayerException e) {
        LogUtil.d(TAG, "Listener播放器错误");
        for (IPlayViewCallBack callBack : mIPlayViewCallBacks) {
            callBack.toast("播放器出现错误");
        }
        return false;
    }
    //==========================  播放器监听事件 end ==============================


    /////////////////////////

}
